﻿using System.IO;
using LC = log4net.Config;
using LM = log4net.LogManager;

namespace Cat.Core.XLog.Log4Net
{
    public sealed class Log4NetProvider : LogProviderBase, ILogProvider
    {
        /// <summary>
        /// 默认文件名
        /// </summary>
        const string c_defaultConfigFileName = "log4net.config";

        /// <summary>
        /// 从xml配置文件初始化log4net
        /// </summary>
        /// <param name="path">配置文件路径,可以是完整文件也可以是文件夹</param>
        /// <param name="watchConfigure">是否监控config文件变化</param>
        public static void Configure(string path, bool watchConfigure = true)
        {
            FileInfo fileInfo = null;
            if (!string.IsNullOrWhiteSpace(path))
            {
                fileInfo = new FileInfo(path);
                //文件不存在 猜测传入的是文件夹
                if (fileInfo.Exists == false)
                {
                    string fileName = Path.Combine(path, c_defaultConfigFileName);
                    fileInfo = new FileInfo(fileName);
                }
            }
            else
            {
                fileInfo = new FileInfo(c_defaultConfigFileName);
            }
            if (fileInfo.Exists)
            {
                if (watchConfigure)
                {
                    LC.XmlConfigurator.ConfigureAndWatch(fileInfo);
                }
                else
                {
                    LC.XmlConfigurator.Configure(fileInfo);
                }
            }
            Log.Provider = Log4NetProvider.Instance;
        }

        public static ILogProvider Instance { get; } = new Log4NetProvider();
        private Log4NetProvider() { }

        protected override ILogger GetLoggerCore(string name)
        {
            var logger = LM.GetLogger(name);
            var result = new Log4NetLogger(logger);
            return result;
        }

        public ILogger GetLogger(string repository, string name)
        {
            //log4net的repository需要结合配置文件，不能随便填写
            if (string.IsNullOrEmpty(repository))
            {
                return GetLogger(name);
            }
            else
            {
                if (string.IsNullOrEmpty(name)) name = "default";
                var logger = LM.GetLogger(name);
                var result = new Log4NetLogger(logger);
                return result;
            }
        }
    }
}
